package com.jianzhile.jobs.activities;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jianzhile.jobs.R;
import com.jianzhile.jobs.base.BaseActivity;
import com.jianzhile.jobs.bean.User;
import com.jianzhile.jobs.utils.CommonUtil;
import com.jianzhile.jobs.utils.Const;
import com.jianzhile.jobs.utils.HttpUtil;
import com.jianzhile.jobs.utils.SharePreUtil;
import com.jianzhile.jobs.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class RegistActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.content_regist_phone_et)
    public EditText phoneEt;
    @Bind(R.id.content_regist_code_et)
    public EditText codeEt;
    @Bind(R.id.content_regist_get_code_btn)
    public Button getCodeBtn;
    @Bind(R.id.content_regist_password_to_see_ib)
    public ImageButton seePassIb;
    @Bind(R.id.content_regist_password_et)
    public EditText passwordEt;
    @Bind(R.id.content_regist_get_in_btn)
    public Button getInBtn;

    private CountDownTimer timer;


    @Override
    public void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_regist);
        ButterKnife.bind(this);
    }

    @Override
    public void setListener() {
        getCodeBtn.setOnClickListener(this);
        seePassIb.setOnClickListener(this);
        getInBtn.setOnClickListener(this);
    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.content_regist_get_code_btn:
                codeEt.requestFocus();
                getAuthCode();
                break;
            case R.id.content_regist_get_in_btn:
                regist();
                break;
            case R.id.content_regist_password_to_see_ib:

                break;
        }
    }


    private void regist() {
        if (!phoneEt.getText().toString().trim().matches("^1[345678]\\d{9}$")) {
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        if (TextUtils.isEmpty(codeEt.getText().toString().trim())) {
            showTipsDialog(R.string.input_code);
            return;
        }
        // 封装请求数据信息
        Map<String, String> params = new HashMap<String, String>();
        params.put("mobile", phoneEt.getText().toString());
        params.put("code", codeEt.getText().toString());
        params.put("password", passwordEt.getText().toString());
        HttpUtil.getInstance().requestWithSecurity(context, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.optInt("code");
                    if (Const.status_1 == code) {
                        String data = jsonObject.optString("data");
                        Gson gson = new Gson();
                        User user = gson.fromJson(data, User.class);
                        if (user != null) {
                            mApplication.mUser = user;
                            mApplication.isLogin = true;
                            //XGPushManager.registerPush(context, user.uuid);
                            SharePreUtil.getInstance().putString(Const.USER, gson.toJson(user));
                            SharePreUtil.getInstance().putString("user_phone", user.mobile);

                            Intent intent = new Intent(RegistActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }

                    } else {
                        ToastUtils.showBottomToast(context, jsonObject.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ToastUtils.showBottomToast(context, R.string.tips);
            }
        }, CommonUtil.getInstance().getParams(params), Const.Register, true);
    }

    private void getAuthCode() {
        if (!phoneEt.getText().toString().trim().matches("^1[345678]\\d{9}$")) {
            showTipsDialog(R.string.phone_num_error);
            return;
        }
        // 封装请求数据信息
        Map<String, String> params = new HashMap<String, String>();
        params.put("mobile", phoneEt.getText().toString());
        HttpUtil.getInstance().requestWithSecurity(this, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.optInt("code");
                    if (Const.status_1 == code) {
                        refreshUI();
                    } else {
                        ToastUtils.showBottomToast(context, jsonObject.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ToastUtils.showBottomToast(context, R.string.tips);
            }
        }, CommonUtil.getInstance().getParams(params), Const.UserCode, true);

    }

    private void refreshUI() {
        getCodeBtn.setEnabled(false);
        if (timer != null) {
            timer.cancel();
        }
        timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                getCodeBtn.setText(getString(R.string.re_get_code, millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                getCodeBtn.setEnabled(true);
                getCodeBtn.setText(getString(R.string.get_auth_code));
            }
        };
        timer.start();
    }

    private void showTipsDialog(int tipsStringId) {
        final Dialog dialog = new Dialog(this, R.style.prompt_progress_dailog_dimenabled);
        dialog.setContentView(R.layout.modify_dialog_layout);
        TextView content = (TextView) dialog.getWindow().getDecorView().findViewById(R.id.tv_content);
        content.setText(getString(tipsStringId));
        TextView sure = (TextView) dialog.getWindow().getDecorView().findViewById(R.id.tv_confirm);
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.TOP); // 设置生效
        // lp.x = 266; // 新位置X坐标
        lp.y = CommonUtil.dip2px(context, 180); // 新位置Y坐标
        // lp.width = 300; // 宽度
        // lp.height = 300; // 高度
        // lp.alpha = 0.7f; // 透明度
        dialogWindow.setAttributes(lp);
        dialog.show();
    }
}
